<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>水平垂直居中对齐</title>
</head>

<style>
   /* 第一种写法 flex 布局写法  父元素用 display  justify-content: center; align-items: center; 一定要写在父元素下 */
  .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    display: flex;
    justify-content: center; 
    align-items: center;
  } 

  .child {
    width: 100px;
    height: 100px;
    background-color: red;
  }


  /* margin: auto; 这种写法代替了 justify-content: center， 这种写法 margin 不能是 margin: 0 auto */
  /* .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    display: flex;
  } 
  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    margin: auto;
    align-items: center;
  } */


   /* 第二种写法  知道子元素固定宽高 */
  .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    position: relative;
  } 

  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    /* 上面的top/left 50% 占了总体的50%，但是子元素被挤到下面的50%， 导致要减去自身的一半，取子元素长高一般即可实现对齐  */
    margin-top: -50px;
    margin-left: -50px;
  }

  /* 第三种写法 transform: translate */
  
  /* .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    position: relative;
  }
  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  } */

  /* 第四种写法 */
 /* .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    position: relative;
  }
  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  } */


  /* .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    text-align: center;
    line-height: 300px;
  }
  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    display: inline-block;
    /* 文本与块元素对齐 
    vertical-align: middle;  
    line-height: initial;
  }  */


  /* 第五种 grid */

  /* .parent {
    width: 300px;
    height: 300px;
    background-color: pink;
    display: grid;
  }

  .child {
    width: 100px;
    height: 100px;
    background-color: red;
    align-self: center;
    justify-self: center;
  } */






</style>
<body>

  <div class="parent">
    <div class="child"></div>
  </div>
  
</body>
</html>